package com.isesol.checkupdate;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.arialyy.downloadutil.DownLoadUtil;
import com.arialyy.downloadutil.Util;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by june on 2016/9/13.
 */
public class VersionActivity  extends Activity {

    private final String TAG = this.getClass().getName();
    private final int UPDATA_NONEED = 0;
    private final int UPDATA_CLIENT = 1;
    private final int GET_UNDATAINFO_ERROR = 2;
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;
    private Button getVersion;
    private UpdataInfo info;
    private String localVersion;
    private TextView tv ;

    private static final int DOWNLOAD_PRE = 0x01;
    private static final int DOWNLOAD_STOP = 0x02;
    private static final int DOWNLOAD_FAILE = 0x03;
    private static final int DOWNLOAD_CANCEL = 0x04;
    private static final int DOWNLOAD_RESUME = 0x05;
    private static final int DOWNLOAD_COMPLETE = 0x06;
    private ProgressBar mPb;
    private String mDownloadUrl = "http://static.gaoshouyou.com/d/12/0d/7f120f50c80d2e7b8c4ba24ece4f9cdd.apk";
    private DownLoadUtil mUtil;
    private Button mStart, mStop, mCancel;
    private TextView mSize;

    private Handler mUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD_PRE:
                    mSize.setText(Util.formatFileSize((Long) msg.obj));
                    mStart.setEnabled(false);
                    break;
                case DOWNLOAD_FAILE:
                    Toast.makeText(VersionActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
                case DOWNLOAD_STOP:
                    Toast.makeText(VersionActivity.this, "暂停下载", Toast.LENGTH_SHORT).show();
                    mStart.setText("恢复");
                    mStart.setEnabled(true);
                    break;
                case DOWNLOAD_CANCEL:
                    mPb.setProgress(0);
                    Toast.makeText(VersionActivity.this, "取消下载", Toast.LENGTH_SHORT).show();
                    mStart.setEnabled(true);
                    mStart.setText("开始");
                    break;
                case DOWNLOAD_RESUME:
                    Toast.makeText(VersionActivity.this, "恢复下载，恢复位置 ==> " + Util.formatFileSize((Long) msg.obj), Toast.LENGTH_SHORT).show();
                    mStart.setEnabled(false);
                    break;
                case DOWNLOAD_COMPLETE:
                    Toast.makeText(VersionActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                    mStart.setEnabled(true);
                    mCancel.setEnabled(false);
                    mStop.setEnabled(false);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

        /**
         * 显示当前版本
         */
        getVersion = (Button) findViewById(R.id.btnUpdate);
        tv = (TextView) this.findViewById(R.id.textView);
        try {
            tv.setText(String.valueOf(getVersionName()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * 检查更新
         */
        checkForUpdate();

        /**
         * Android-M 动态申请权限
         */
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }

    }

    private void init() {
        mPb = (ProgressBar) findViewById(R.id.progressBar);
        mStart = (Button) findViewById(R.id.start);
        mStop = (Button) findViewById(R.id.stop);
        mCancel = (Button) findViewById(R.id.cancel);
        mSize = (TextView) findViewById(R.id.size);
        mUtil = new DownLoadUtil();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:
                start();
                break;
            case R.id.stop:
                stop();
                break;
            case R.id.cancel:
                cancel();
                break;
        }
    }

    private void start() {
        mUtil.download(this, mDownloadUrl, Environment.getExternalStorageDirectory().getPath() + "/test.apk"
                , new DownLoadUtil.DownloadListener() {
            long fileSize = 1;

            @Override
            public void onPreDownload(HttpURLConnection connection) {
                super.onPreDownload(connection);
                mPb.setMax(100);
                fileSize = connection.getContentLength();
                mUpdateHandler.obtainMessage(DOWNLOAD_PRE, fileSize).sendToTarget();
            }

            @Override
            public void onStart(long startLocation) {
                super.onStart(startLocation);
            }

            @Override
            public void onChildResume(long resumeLocation) {
                super.onChildResume(resumeLocation);
            }

            @Override
            public void onChildComplete(long finishLocation) {
                super.onChildComplete(finishLocation);
            }

            @Override
            public void onProgress(long currentLocation) {
                super.onProgress(currentLocation);
                mPb.setProgress((int) (currentLocation * 100 / fileSize));
            }

            @Override
            public void onStop(long stopLocation) {
                super.onStop(stopLocation);
                mUpdateHandler.obtainMessage(DOWNLOAD_STOP).sendToTarget();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                mUpdateHandler.obtainMessage(DOWNLOAD_CANCEL).sendToTarget();
            }

            @Override
            public void onResume(long resumeLocation) {
                super.onResume(resumeLocation);
                mUpdateHandler.obtainMessage(DOWNLOAD_RESUME, resumeLocation).sendToTarget();
            }

            @Override
            public void onFail() {
                super.onFail();
                mUpdateHandler.obtainMessage(DOWNLOAD_FAILE).sendToTarget();
            }

            @Override
            public void onComplete() {
                super.onComplete();
                mUpdateHandler.obtainMessage(DOWNLOAD_COMPLETE).sendToTarget();
            }
        });
    }

    private void stop() {
        mUtil.stopDownload();
    }

    private void cancel() {
        mUtil.cancelDownload();
    }


    public void checkForUpdate(){

        try {
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
                0);
        return packInfo.versionName;
    }

    public class CheckVersionTask implements Runnable {
        InputStream is;
        public void run() {
            try {
                String path = getResources().getString(R.string.url_server);
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    is = conn.getInputStream();
                }
                info = UpdataInfoParser.getUpdataInfo(is);
                if (info.getVersion().equals(localVersion)) {
                    Log.i(TAG, "版本号相同");
                    Message msg = new Message();
                    msg.what = UPDATA_NONEED;
                    handler.sendMessage(msg);
                    // LoginMain();
                } else {
                    Log.i(TAG, "版本号不相同 ");
                    Message msg = new Message();
                    msg.what = UPDATA_CLIENT;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UNDATAINFO_ERROR;
                handler.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATA_NONEED:
                    Toast.makeText(getApplicationContext(), "当前已是最新版本，无需更新",
                            Toast.LENGTH_SHORT).show();
                    break;
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", Toast.LENGTH_SHORT).show();
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    Toast.makeText(getApplicationContext(), "下载新版本失败",  Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    /*
     *
     * 弹出对话框通知用户更新程序
     *
     * 弹出对话框的步骤：
     *  1.创建alertDialog的builder.
     *  2.要给builder设置属性, 对话框的内容,样式,按钮
     *  3.通过builder 创建一个对话框
     *  4.对话框show()出来
     */
    protected void showUpdataDialog() {

        AlertDialog.Builder builer = new Builder(this);
        builer.setTitle("版本升级");
        builer.setMessage(info.getDescription());
        //当点确定按钮时从服务器上下载 新的apk 然后安装   װ
        builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG, "下载apk,更新");
                downLoadApk();
            }
        });
        builer.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                //do sth
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();

    }

    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {

        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    mDownloadUrl = info.getUrl();
                    start();
                    File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);

                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                    

                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
            }}.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
